package com.kurumi.medical.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kurumi.medical.comparator.MapComparator;
import com.kurumi.medical.component.MyConfig;
import com.kurumi.medical.log.ExceptionLog;
import com.kurumi.medical.model.HospitalVisitExaminationReportsInfo;
import com.kurumi.medical.model.HospitalVisitProgressNote;
import com.kurumi.medical.model.HospitalVisitRecordSheet;
import com.kurumi.medical.page.DPage;
import com.kurumi.medical.pojo.HospNoteVersion;
import com.kurumi.medical.pojo.RespondResult;
import com.kurumi.medical.pojo.User;
import com.kurumi.medical.service.Export305DateService;
import com.kurumi.medical.service.ExportDataService;
import com.kurumi.medical.service.HospNoteBasicJsonService;
import com.kurumi.medical.service.HospitalNoteVersionService;
import com.kurumi.medical.service.HospitalVisit305Service;
import com.kurumi.medical.util.CookieUtils;
import com.kurumi.medical.util.DateUtil;
import com.kurumi.medical.util.ExceptionUtil;
import com.kurumi.medical.util.FileUtil;
import com.kurumi.medical.util.FtpClientUtil;
import com.kurumi.medical.util.JsonUtil;
import com.kurumi.medical.util.JsonUtils;
import com.kurumi.medical.util.MysqlDataTable;
import com.kurumi.medical.util.OracleDataTable;
import com.kurumi.medical.util.Result;
import com.kurumi.medical.util.StringUtil;
import com.kurumi.medical.util.disk.DiskManageUtil;
import com.kurumi.medical.vo.PatVisitVO;

@Controller
@RequestMapping("/export305")
public class Export305DataController {
	private static final Logger log = LoggerFactory.getLogger(Export305DataController.class);
	
	@Autowired
	private ExportDataService exportDataService;
	
	@Autowired
	private HospitalVisit305Service hospitalVisitService;
	
	@Autowired
	private HospitalNoteVersionService hospitalNoteVersionService;
	
	@Autowired
	private MyConfig myConfig;
	
	
	@Autowired
	private Export305DateService export305DateService;
	
	@Autowired
	private HospNoteBasicJsonService hospNoteBasicJsonService;
	
	@Autowired
	private HospitalVisit305Service hospitalVisit305Service;
	
	
	
	@GetMapping("/exportData")
	public String exportData(String outHospitalStartDate,String outHospitalEndDate){
		List<Map<String, Object>> datas = null;
		if((outHospitalStartDate != "" && outHospitalStartDate != null) || (outHospitalEndDate!="" && outHospitalEndDate != null) ){
			datas = hospitalVisitService.queryOracleMedicalHospitalVisit(outHospitalStartDate,outHospitalEndDate,null,null,null);
			System.out.println(datas.size());
			for (Map<String, Object> data : datas) {
				String mrId = (String)data.get("MRID");
				BigDecimal visitNumber = (BigDecimal)data.get("VISITNUMBER");
				String onlyId = (String)data.get("ONLYID");
				int count = hospitalVisitService.getHospitalizationNoteCountByMrIdAndOnlyId(mrId,visitNumber.intValue());
				if(count > 0){
					continue;
				}else{
					try {
						
					
					User currentUser = new User();
					Result resultOracleDatas = hospitalVisitService.getDatasByOracle(mrId,visitNumber.intValue());
					
					if (resultOracleDatas.isSuccess()) {
						hospitalVisitService.insertHospitalVisitRecords((List<Map<String, Object>>)resultOracleDatas.getData(),currentUser);
					}
					
					} catch (Exception e) {
						continue;
					}
				}
			}
			}
		return "success";
	}
	
	//@RequiresPermissions("data_pull")
	@ResponseBody
	@GetMapping("/ajaxExportMedicalVisitJson")
	public Result queryExportMedicalVisitPage(HttpServletResponse response,PatVisitVO patVisitVO){
		 response.setHeader("Access-Control-Allow-Origin", "*");
		 
		 /*PageHelper.startPage(patVisitVO.getPageNo(),patVisitVO.getPageSize());*/
		 List<Map<String,Object>> hospitalVisits = hospitalVisitService.queryOracleMedicalHospitalVisit(patVisitVO.getStartDate(), patVisitVO.getEndDate(),patVisitVO.getMrId(),patVisitVO.getVisitNumber(),patVisitVO.getOutDeptCode());
		 for (Map<String, Object> data : hospitalVisits) {
			 String mrId = (String)data.get("MRID");
			 BigDecimal visitNumber = (BigDecimal)data.get("VISITNUMBER");
			 String onlyId = (String)data.get("ONLYID");
			 int count = hospitalVisitService.getHospitalizationNoteCountByMrIdAndOnlyId(mrId,visitNumber.intValue());
			 if(count > 0){
				 data.put("new_record", "0");
			 }else{
				 data.put("new_record", "1");
			 }
		}
		Collections.sort(hospitalVisits, new MapComparator("new_record"));
		DPage<Map<String, Object>> dPage = new DPage<Map<String, Object>>(hospitalVisits,patVisitVO.getPageNo(),patVisitVO.getPageSize());
		/*PageInfo pageInfo = new PageInfo(hospitalVisits);
		List<Map<String,Object>> list =pageInfo.getList();*/
		
		/*PageInfo pageInfo = hospitalVisitService.getOracleMedicalPageHospitalVisit(patVisitVO);
		 List<Map<String,Object>> list =pageInfo.getList();
		 for (Map<String, Object> data : list) {
				String mrId = (String)data.get("MRID");
				BigDecimal visitNumber = (BigDecimal)data.get("VISITNUMBER");
				String onlyId = (String)data.get("ONLYID");
				int count = hospitalVisitService.getHospitalizationNoteCountByMrIdAndOnlyId(mrId,visitNumber.intValue());
				if(count > 0){
					data.put("new_record", "0");
				}else{
					data.put("new_record", "1");
				}
		}
		Collections.sort(list, new MapComparator("new_record"));*/
		return new Result(true,"查询成功!",dPage);
	}
	
	
	//@RequiresPermissions("data_pull")
	@GetMapping("/queryExportMedicalVisitForm")
	public String queryExportMedicalVisitForm(String outHospitalStartDate,String outHospitalEndDate, String patientId,Integer visitNum,Model model){
		List<Map<String, Object>> datas = null;
		if((outHospitalStartDate != "" && outHospitalStartDate != null) || (outHospitalEndDate!="" && outHospitalEndDate != null) || (patientId!=null && patientId!="") || visitNum!=null){
			datas = hospitalVisitService.queryOracleMedicalHospitalVisit(outHospitalStartDate,outHospitalEndDate,patientId,visitNum,null);
			for (Map<String, Object> data : datas) {
				String mrId = (String)data.get("MRID");
				BigDecimal visitNumber = (BigDecimal)data.get("VISITNUMBER");
				String onlyId = (String)data.get("ONLYID");
				int count = hospitalVisitService.getHospitalizationNoteCountByMrIdAndOnlyId(mrId,visitNumber.intValue());
				if(count > 0){
					data.put("new_record", "0");
				}else{
					data.put("new_record", "1");
				}
			}
		}
		String jsonData = JsonUtil.objectToJson(datas);
		model.addAttribute("jsonData", jsonData);
		model.addAttribute("outHospitalStartDate", outHospitalStartDate);
		model.addAttribute("patientId", patientId);
		model.addAttribute("visitNum", visitNum);
		model.addAttribute("outHospitalEndDate", outHospitalEndDate);
		return "query/queryHospitalVisit";
	}
	
	
	@GetMapping("/queryMedicalVisitScanForm")
	public String queryMedicalVisitScanForm(String mrId,Integer visitNumber, Model model){
		List<Map<String, Object>> datas = null;
		if(mrId != null && visitNumber != null){
			datas = hospitalVisitService.queryOracleMedicalHospitalRecord(mrId,visitNumber);
			
			for (Map<String, Object> data : datas) {
				String currentMrId = (String)data.get("MRID");
				BigDecimal currentVisitNumber = (BigDecimal)data.get("VISITNUMBER");
				String onlyId = (String)data.get("ONLYID");
				int count = hospitalVisitService.getHospitalizationNoteCountByMrIdAndOnlyId(mrId,currentVisitNumber.intValue());
				if(count > 0){
					data.put("new_record", "0");
				}else{
					data.put("new_record", "1");
				}
			}
		}
		String jsonData = JsonUtil.objectToJson(datas);
		model.addAttribute("mrId", mrId);
		model.addAttribute("visitNumber", visitNumber);
		model.addAttribute("jsonData", jsonData);
		
		return "query/queryHospitalVisit";
	}
	
	
	/**
	 * 根据mrId和visitNumber抓取305病案数据
	 * @param response
	 * @param request
	 * @param params
	 * @return
	 */
	@ResponseBody
	@GetMapping("/ajaxFetchDataByMrIdAndVisitNumber")
	public Result ajaxFetchDataByMrIdAndVisitNumber(HttpServletResponse response,HttpServletRequest request,String params){
		response.setHeader("Access-Control-Allow-Origin", "*");
		
		Result result =null;
		String userId = CookieUtils.getCookieValue(request, "TT_TOKEN");
		String userName = CookieUtils.getCookieValue(request, "userName");
		User currentUser = new User();
		currentUser.setLoginName(userId);
		currentUser.setName(userName);
		
		try {
			if(StringUtils.isNotBlank(params)){
				String[] array= params.split("--");
				for (String string : array) {
					String mrId=string.split("-")[0];
					String visitNumber=string.split("-")[1];
					//获取病案整个数据包 List<Map<String, Object>>
					Result resultDatas = hospitalVisitService.getDatasByOracle(mrId,Integer.valueOf(visitNumber));
					
					if (!resultDatas.isSuccess()) {
						return resultDatas;
					}
					
					List<Map<String, Object>> datas = (List<Map<String, Object>>)resultDatas.getData();
					
					
					
					hospitalVisitService.insertHospitalVisitRecords(datas,currentUser);
				}
			}
						
			result = new Result(true,"查询成功!");
		} catch (Exception e) {
			e.printStackTrace();
			result = new Result(false,"查询失败");
		}
		return result;
	}
	
	/**
	 * 根据mrId和visitNumber抓取305病案数据
	 * @param response
	 * @param request
	 * @param params
	 * @return
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 */
	@ResponseBody
	@GetMapping("/ajaxFetchDataByMrIdAndVisitNumber1")
	public Result ajaxFetchDataByMrIdAndVisitNumber1(HttpServletResponse response,HttpServletRequest request,String params) throws FileNotFoundException, IOException{
		response.setHeader("Access-Control-Allow-Origin", "*");
		
		List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>();
		
		String jsonStr = IOUtils.toString(new FileInputStream(new File("D:\\publics\\hospital\\visit\\json\\68\\1e\\02\\88\\681e0288efa144d295cb6319488ef88b.json")), "utf-8");
		Map<String, Object> jsonMap = JsonUtils.jsonToPojo(jsonStr, Map.class);
		datas.add(jsonMap);
		User currentUser = new User();
		currentUser.setLoginName("1");
		currentUser.setName("张三");
		
		hospitalVisitService.insertHospitalVisitRecords(datas, currentUser);
						
		return new Result(true,"查询成功!");
	}
	
	
	/**
	 * 重复提取检验报告单
	 * 
	 * @param visitGuid
	 * @param mrId
	 * @param visitNumber
	 * @param request
	 * @param response
	 * @return
	 */
	@GetMapping("/ajaxRepeatFetchExaminationReportsInfoByMrIdAndVisitNumber")
	@ResponseBody
	public Result ajaxRepeatFetchExaminationReportsInfoByMrIdAndVisitNumber(String visitGuid, String mrId, Integer visitNumber, String dateStr, 
			HttpServletRequest request, HttpServletResponse response) {
		Result result = null;
		response.setHeader("Access-Control-Allow-Origin", "*");
		
		if (StringUtils.isBlank(visitGuid) || StringUtils.isBlank(mrId) || null == visitNumber) {
			return new Result(false, "visitGuid为空,或者病案号为空,或者住院次数为空!", null);
		}
		
		List<Map<String, Object>> hospitalVisitInfos = null;
		
		
		try {
			 hospitalVisitInfos = hospitalVisit305Service.getHospitalVisit305InfoByOracleByMrIdAndVisitNumber(mrId, visitNumber);
		} catch (Exception e) {
			return new Result(false, "从信息科数据库里面查询病案基本数据异常" + ExceptionUtil.getStackTrace(e));
		}
		
		if (null == hospitalVisitInfos || hospitalVisitInfos.size() == 0) {
			return new Result(false, "通过" + mrId + "-" + visitNumber + "到信息科数据库里面没有查询到病案,请联系信息科");
		}
		
		//[start] 设置病案检验报告单信息
		HospitalVisitExaminationReportsInfo examinationReportsInfo = new HospitalVisitExaminationReportsInfo();
		examinationReportsInfo.setVisitGuid(visitGuid);
		
			String preFileName = visitGuid + "_" + mrId + "_" + visitNumber + "_";
			String destPath = myConfig.getExaminationLocalDir() + visitGuid + "/" + visitGuid + "_" + dateStr;
			Result reportResult = hospitalVisit305Service.getRepeatFetchExaminationReportsInfo(hospitalVisitInfos.get(0), visitGuid, destPath);
					
			if (!reportResult.isSuccess()) {
				return reportResult;
			}
			
			examinationReportsInfo = (HospitalVisitExaminationReportsInfo)reportResult.getData();
			
			if (examinationReportsInfo.getExaminationReportsRecords().size() == 0) {
				return new Result(false, "从Lis里面获取检验报告单数据为空!");
			}
			
		  return new Result(true, "success", JsonUtils.objectToJson(examinationReportsInfo), 200);
	}
	
	
	/**
	 * 重新提取病程记录
	 * @param visitGuid
	 * @param mrId
	 * @param visitNumber
	 * @param request
	 * @param response
	 * @return
	 */
	@GetMapping("/ajaxRepeatFetchProgressNoteDataByMrIdAndVisitNumber")
	@ResponseBody
	public Result ajaxRepeatFetchProgressNoteDataByMrIdAndVisitNumber(String visitGuid, String mrId, Integer visitNumber, 
			HttpServletRequest request, HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		HospitalVisitProgressNote progressNote = new HospitalVisitProgressNote();
		progressNote.setVisitGuid(visitGuid);
		List<String> fileNameList = null;
		
		//ftp上病程记录的路径
		String progressNoteFolder  = StringUtil.ftpFolderGenerator(mrId, visitNumber);
		//本地临时目录
		String localTempProgressNoteFolder = myConfig.getProgressNoteDir()+"temp/" + StringUtil.getId();
		File tempProgressNoteFile = new File(localTempProgressNoteFolder);
		
		if (!tempProgressNoteFile.isDirectory()) {
			synchronized (myConfig.getProgressNoteDir()) {
				tempProgressNoteFile.mkdirs();
			}
		}
		
		Result result = null;
		String dateStr = DateUtil.dateFormat("yyyyMMddHHmmssssss", new Date());
		String preFileName = visitGuid + "_" + mrId + "_" + visitNumber + "_";
		
		try {
			 //下载ftp服务器上的html到本地临时文件夹
			 result = FtpClientUtil.downProgressNoteFile(myConfig.getFtpHost(), myConfig.getFtpPort(), myConfig.getFtpUsername(), myConfig.getFtpPassword(), 
					 progressNoteFolder, localTempProgressNoteFolder);
			
			if (result.isSuccess()) {
				fileNameList = (List<String>)result.getData();
				if (fileNameList.size() == 0) {
					/*ExceptionLog exceptionLog = new ExceptionLog();
					exceptionLog.setLogContent("ftp服务器上资源不存在");
					exceptionLog.setLogFilePath(myConfig.getProgressNoteDir()+"log");
					exceptionLog.setLogFileName(preFileName + dateStr + ".log");
					exceptionLog.writeLog();*/
					result = new Result(false, "ftp服务器上资源不存在", null, -3);
				} else {
					//真实保存的路径
					String localActualDir = myConfig.getProgressNoteDir() + visitGuid + "/" + visitGuid + "_" + dateStr;
					File localActualDirFile = new File(localActualDir);
					
					if (!localActualDirFile.isDirectory()) {
						synchronized (myConfig.getProgressNoteDir()) {
							localActualDirFile.mkdirs();
						}
					}
					
					Result copyResult = FileUtil.copyFiles(fileNameList, localActualDir, localTempProgressNoteFolder, visitGuid + "_" + dateStr);
					
					//复制失败
					if (!copyResult.isSuccess()) {
						ExceptionLog exceptionLog = new ExceptionLog();
						exceptionLog.setLogContent(copyResult.getMsg());
						exceptionLog.setLogFilePath(myConfig.getProgressNoteDir()+"log");
						exceptionLog.setLogFileName(preFileName + dateStr + ".log");
						exceptionLog.writeLog();
						
						//删除复制失败的文件
						FileUtil.deleleDirAllFile(localActualDir);
						result = new Result(false, "本地复制病程记录文件失败" + copyResult.getMsg(), null, -5);
					} else {
						progressNote.setProgressList((List<String>)copyResult.getData());
						
						//更新json里面的病程记录
						String filePath = myConfig.getHospitalVisitJsonPath() + StringUtil.getLocalPath(visitGuid);
						String fileName = visitGuid + ".json";
						String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + visitGuid + "/";
						// 版本文件名称
						String versionFileName = dateStr + ".json";

						String diskName = DiskManageUtil.getDiskNameByFileName(myConfig.getConfigFileStorageAllDisk(), filePath + fileName);
						String realFilePath = diskName + filePath.trim().substring(1);
						
						if (StringUtils.isBlank(diskName)) {
							log.error("本地磁盘{}里面没有找到json文件, filePath={}, visitGuid", myConfig.getConfigFileStorageAllDisk(), 
									filePath + fileName, visitGuid);
							return new Result(false, "本地json文件不存在", null, -6);
						} 
						
						Map<String, Object> jsonMap = null;
						
						try {
							 jsonMap = FileUtil.readLineFile1(realFilePath, fileName);
						} catch (Exception e) {
							log.error("读取本地json文件异常, filePath={}, visitGuid={}, exceptionMsg={}", realFilePath,
									visitGuid, ExceptionUtil.getStackTrace(e));
							return new Result(false, "读取本地json文件异常", null, -7);
						}
						
						String currentUser = CookieUtils.getCookieValue(request, "userName");
						jsonMap.put("userId", currentUser);
						jsonMap.put("progressNote", progressNote);
						String jsonMapJson = JsonUtil.objectToJson(jsonMap);
							
							try {
								FileUtil.createOrEditFile(jsonMapJson, realFilePath, fileName);
								
							} catch (IOException io) {
								//保存本地json文件失败 
								ExceptionLog exceptionLog = new ExceptionLog();
								exceptionLog.setLogContent("保存本地json文件失败----" + ExceptionUtil.getStackTrace(io));
								exceptionLog.setLogFilePath(myConfig.getProgressNoteDir()+"log");
								exceptionLog.setLogFileName(preFileName + dateStr + ".log");
								exceptionLog.writeLog();
								//删除已经保存病程记录html
								FileUtil.deleleDirAllFile(localActualDir);
								return new Result(false, "保存本地json文件异常  "+ExceptionUtil.getStackTrace(io), null, 500);
							}
							
							try {
								FileUtil.createOrEditFile(jsonMapJson, versionFilePath, versionFileName);
							} catch (IOException io) {
								//保存本地json文件失败  这个可以手动去同步
								ExceptionLog exceptionLog = new ExceptionLog();
								exceptionLog.setLogContent("保存本地json版本文件失败----jsonMapJson=" + jsonMapJson + " versionFilePath=" + versionFilePath + 
										" versionFileName="+versionFileName + ExceptionUtil.getStackTrace(io));
								exceptionLog.setLogFilePath(myConfig.getProgressNoteDir()+"log");
								exceptionLog.setLogFileName(preFileName + dateStr+"_saveLocalJsonFile" + ".log");
								exceptionLog.writeLog();
								//删除已经保存病程记录html
							}
							
							//记录版本
							HospNoteVersion hospNoteVersion = new HospNoteVersion();
							try {
								hospNoteVersion.setCreateTime(new Date());
								hospNoteVersion.setFirstGuid(visitGuid);
								hospNoteVersion.setFileName(versionFileName);
								hospNoteVersion.setOperator(currentUser);
								hospitalNoteVersionService.insertHospitalNoteVersion(hospNoteVersion);
							} catch (Exception e) {
								ExceptionLog exceptionLog = new ExceptionLog();
								exceptionLog.setLogContent("---hospNoteVersion保存到数据库失败--visitGuid=" + visitGuid + 
										" versionFileName=" + versionFileName + " currentUser=" +currentUser);
								exceptionLog.setLogFilePath(myConfig.getProgressNoteDir()+"log");
								exceptionLog.setLogFileName(preFileName + dateStr+"_insertHospNoteVersionDataBase" + ".log");
								exceptionLog.writeLog();
							}
							
							String hospitalVisitDataJson = null;
							try {
								hospitalVisitDataJson = hospNoteBasicJsonService.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitGuid));
							} catch (Exception e) {
								//需要删除本地json版本和数据库版本
								ExceptionLog exceptionLog = new ExceptionLog();
								exceptionLog.setLogContent("查询导致数据库系统异常  visitGuid="+ visitGuid + " hospNoteVersionId=" + hospNoteVersion.getId()
										+ " versionFilePath=" + versionFilePath + " versionFileName=" + versionFileName
										+ ExceptionUtil.getStackTrace(e) );
								exceptionLog.setLogFilePath(myConfig.getProgressNoteDir()+"log");
								exceptionLog.setLogFileName(preFileName + dateStr+ "_selectHospNoteBasicJsonDatabase"+ ".log");
								exceptionLog.writeLog();
								FileUtil.deleleDirAllFile(localActualDir);
								return new Result(false, "查询导致数据库系统异常"+ExceptionUtil.getStackTrace(e), null, 500);
							}
							
							Map<String, Object> jsonDataMap = new HashMap<String, Object>();
							
							//保存病程记录到数据库json中
							if (hospitalVisitDataJson != null) {
								jsonDataMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
								jsonDataMap.put("progressNote", progressNote);
								
								try {
									hospNoteBasicJsonService.updateHospBasicJsonByFirstGuid(visitGuid,
											JsonUtils.objectToJson(jsonDataMap));
								} catch (Exception e) {
									//需要删除本地json版本和数据库版本
									ExceptionLog exceptionLog = new ExceptionLog();
									exceptionLog.setLogContent("写入数据库异常  visitGuid="+ visitGuid + " hospNoteVersionId=" + hospNoteVersion.getId()
											+ " versionFilePath=" + versionFilePath + " versionFileName=" + versionFileName
											+ ExceptionUtil.getStackTrace(e) );
									exceptionLog.setLogFilePath(myConfig.getProgressNoteDir()+"log");
									exceptionLog.setLogFileName(preFileName + dateStr+ "_insertHospNoteBasicJsonDatabase"+ ".log");
									exceptionLog.writeLog();
									result = new Result(false, "系统异常"+ExceptionUtil.getStackTrace(e), null, 500);
									FileUtil.deleleDirAllFile(localActualDir);
								} 
								
							} else {
								jsonDataMap.put("firstGuid", visitGuid);
								jsonDataMap.put("progressNote", progressNote);
								
								try {
									hospNoteBasicJsonService.addHospNoteBasicJson(JsonUtils.objectToJson(jsonDataMap));
								} catch (Exception e) {
									ExceptionLog exceptionLog = new ExceptionLog();
									exceptionLog.setLogContent("写入数据库异常  visitGuid="+ visitGuid + " hospNoteVersionId=" + hospNoteVersion.getId()
									+ " versionFilePath=" + versionFilePath + " versionFileName=" + versionFileName
									+ ExceptionUtil.getStackTrace(e) );
									exceptionLog.setLogFilePath(myConfig.getProgressNoteDir()+"log");
									exceptionLog.setLogFileName(preFileName + dateStr + "_insertHospNoteBasicJsonDatabase" + ".log");
									exceptionLog.writeLog();
									result = new Result(false, "写入数据库系统异常"+ExceptionUtil.getStackTrace(e), null, 500);
									FileUtil.deleleDirAllFile(localActualDir);
								}
						  }
					} }
			}else {
				//从ftp上取数据失败的原因记录到日志里面
				ExceptionLog exceptionLog = new ExceptionLog();
				exceptionLog.setLogContent(result.getMsg());
				exceptionLog.setLogFilePath(myConfig.getProgressNoteDir()+"log");
				exceptionLog.setLogFileName(preFileName + dateStr + ".log");
				exceptionLog.writeLog();
			} } catch(Exception ex) {
				ExceptionLog exceptionLog = new ExceptionLog();
				exceptionLog.setLogContent("系统异常" + ExceptionUtil.getStackTrace(ex));
				exceptionLog.setLogFilePath(myConfig.getProgressNoteDir()+"log");
				exceptionLog.setLogFileName(preFileName + dateStr + ".log");
				exceptionLog.writeLog();
				//删除已经保存病程记录html
				result = new Result(false, "系统异常"+ExceptionUtil.getStackTrace(ex), null, 500);
			} finally {
			//清除临时文件
			FileUtil.deleleDirAllFile(localTempProgressNoteFolder);
		}
		
		return result;
	}
	
	/**
	 * 重新提取护理记录
	 * @param visitGuid
	 * @param mrId
	 * @param visitNumber
	 * @param request
	 * @param response
	 * @return
	 */
	@GetMapping("/ajaxRepeactPdfRecordSheetFormNurse")
	@ResponseBody
	public Result ajaxRepeactPdfRecordSheetFormNurse(String visitGuid, String mrId, Integer visitNumber, 
			HttpServletRequest request, HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		
		String dateStr = DateUtil.dateFormat("yyyyMMddHHmmssssss", new Date());
		String logPath = myConfig.getLogPath() + File.separator + "repeatFetch" + File.separator 
				+ visitGuid + File.separator + visitGuid + "_" + dateStr;
		String preFileName = visitGuid + "_" + mrId +"_" + visitNumber + "_";
		
		try {
			HospitalVisitRecordSheet hospitalVisitRecordSheet  = hospitalVisitService.getRepeactHospitalVisitRecordSheet(visitGuid, mrId, visitNumber + "", dateStr);
			
			if (null == hospitalVisitRecordSheet) {
				return new Result(false, "该病案护理记录没有找到");
			}
			
			//更新json里面的护理记录
			String filePath = myConfig.getHospitalVisitJsonPath() + StringUtil.getLocalPath(visitGuid);
			String fileName = visitGuid + ".json";
			String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + visitGuid + "/";
			// 版本文件名称
			String versionFileName = dateStr + ".json";

			String diskName = DiskManageUtil.getDiskNameByFileName(myConfig.getConfigFileStorageAllDisk(), filePath + fileName);
			
			if (StringUtils.isBlank(diskName)) {
				log.error("本地磁盘{}里面没有找到json文件, filePath={}, visitGuid", myConfig.getConfigFileStorageAllDisk(), 
						filePath + fileName, visitGuid);
				return new Result(false, "本地json文件找不到!", null, 500);
			} 
			
			//写入到本地json文件
			String realFilePath = diskName + filePath.trim().substring(1);
			
			Map<String, Object> jsonMap = FileUtil.readLineFile1(realFilePath, fileName);
			
			String currentUser = CookieUtils.getCookieValue(request, "userName");
			jsonMap.put("userId", currentUser);
			jsonMap.put("recordSheet", hospitalVisitRecordSheet);
			String jsonMapJson = JsonUtil.objectToJson(jsonMap);
			
				try {
					FileUtil.createOrEditFile(jsonMapJson, realFilePath, fileName);
				} catch (IOException io) {
					//保存本地json文件失败 
					ExceptionLog exceptionLog = new ExceptionLog();
					exceptionLog.setLogContent("保存本地json文件失败----" + ExceptionUtil.getStackTrace(io));
					exceptionLog.setLogFilePath(logPath);
					exceptionLog.setLogFileName(preFileName + dateStr + ".log");
					exceptionLog.writeLog();
					//删除已经保存病程记录html
					return new Result(false, "保存本地json文件异常  "+ExceptionUtil.getStackTrace(io), null, 500);
				}
				
				try {
					FileUtil.createOrEditFile(jsonMapJson, versionFilePath, versionFileName);
				} catch (IOException io) {
					//保存本地json文件失败  这个可以手动去同步
					ExceptionLog exceptionLog = new ExceptionLog();
					exceptionLog.setLogContent("保存本地json版本文件失败----jsonMapJson=" + jsonMapJson + " versionFilePath=" + versionFilePath + 
							" versionFileName="+versionFileName + "dateStr=" + dateStr + ExceptionUtil.getStackTrace(io));
					exceptionLog.setLogFilePath(logPath);
					exceptionLog.setLogFileName(preFileName + dateStr + "_saveLocalJsonFile" + ".log");
					exceptionLog.writeLog();
				}
				
				//记录版本
				HospNoteVersion hospNoteVersion = new HospNoteVersion();
				try {
					hospNoteVersion.setCreateTime(new Date());
					hospNoteVersion.setFirstGuid(visitGuid);
					hospNoteVersion.setFileName(versionFileName);
					hospNoteVersion.setOperator(currentUser);
					hospitalNoteVersionService.insertHospitalNoteVersion(hospNoteVersion);
				} catch (Exception e) {
					ExceptionLog exceptionLog = new ExceptionLog();
					exceptionLog.setLogContent("---hospNoteVersion保存到数据库失败--visitGuid=" + visitGuid + 
							" versionFileName=" + versionFileName + " currentUser=" +currentUser + " " + ExceptionUtil.getStackTrace(e));
					exceptionLog.setLogFilePath(logPath);
					exceptionLog.setLogFileName(preFileName + dateStr+"_insertHospNoteVersionDataBase" + ".log");
					exceptionLog.writeLog();
				}
				
				String hospitalVisitDataJson = null;
				try {
					hospitalVisitDataJson = hospNoteBasicJsonService.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitGuid));
				} catch (Exception e) {
					//需要删除本地json版本和数据库版本
					ExceptionLog exceptionLog = new ExceptionLog();
					exceptionLog.setLogContent("查询导致数据库系统异常  visitGuid="+ visitGuid + " hospNoteVersionId=" + hospNoteVersion.getId()
							+ " versionFilePath=" + versionFilePath + " versionFileName=" + versionFileName
							+ ExceptionUtil.getStackTrace(e) );
					exceptionLog.setLogFilePath(logPath);
					exceptionLog.setLogFileName(preFileName + dateStr+ "_selectHospNoteBasicJsonDatabase"+ ".log");
					exceptionLog.writeLog();
					return new Result(false, "查询导致数据库系统异常"+ExceptionUtil.getStackTrace(e), null, 500);
				}
				
				Map<String, Object> jsonDataMap = new HashMap<String, Object>();
				
				//保存病程记录到数据库json中
				if (hospitalVisitDataJson != null) {
					jsonDataMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
					jsonDataMap.put("recordSheet", hospitalVisitRecordSheet);
					
					try {
						hospNoteBasicJsonService.updateHospBasicJsonByFirstGuid(visitGuid,
								JsonUtils.objectToJson(jsonDataMap));
					} catch (Exception e) {
						//需要删除本地json版本和数据库版本
						ExceptionLog exceptionLog = new ExceptionLog();
						exceptionLog.setLogContent("写入数据库异常  visitGuid="+ visitGuid + " hospNoteVersionId=" + hospNoteVersion.getId()
								+ " versionFilePath=" + versionFilePath + " versionFileName=" + versionFileName
								+ ExceptionUtil.getStackTrace(e) );
						exceptionLog.setLogFilePath(logPath);
						exceptionLog.setLogFileName(preFileName + dateStr+ "_insertHospNoteBasicJsonDatabase"+ ".log");
						exceptionLog.writeLog();
						return new Result(false, "写入数据库系统异常 "+ExceptionUtil.getStackTrace(e), null, 500);
					} 
					
				} else {
					jsonDataMap.put("firstGuid", visitGuid);
					jsonDataMap.put("recordSheet", hospitalVisitRecordSheet);
					
					try {
						hospNoteBasicJsonService.addHospNoteBasicJson(JsonUtils.objectToJson(jsonDataMap));
					} catch (Exception e) {
						ExceptionLog exceptionLog = new ExceptionLog();
						exceptionLog.setLogContent("写入数据库异常  visitGuid="+ visitGuid + " hospNoteVersionId=" + hospNoteVersion.getId()
						+ " versionFilePath=" + versionFilePath + " versionFileName=" + versionFileName
						+ ExceptionUtil.getStackTrace(e) );
						exceptionLog.setLogFilePath(logPath);
						exceptionLog.setLogFileName(preFileName + dateStr + "_insertHospNoteBasicJsonDatabase" + ".log");
						exceptionLog.writeLog();
						return new Result(false, "写入数据库系统异常"+ExceptionUtil.getStackTrace(e), null, 500);
					}
			  }
			
		} catch (Exception e) {
			return new Result(false, "系统异常");
		}
		
		return new Result(true, "提取成功");
	}
	
	
	
	@PostMapping("/exportMedicalHospitalRecordByMrIdAndVisitNumber")
	public String exportMedicalHospitalRecordByMrIdAndVisitNumber(String mrId,Integer visitNumber,String patientId,Integer visitNum,String outHospitalStartDate,String outHospitalEndDate,HttpServletRequest request,Model model){
		String userId = CookieUtils.getCookieValue(request, "TT_TOKEN");
		String userName = CookieUtils.getCookieValue(request, "userName");
		User currentUser = new User();
		currentUser.setLoginName(userId);
		currentUser.setName(userName);
		Result resultDatas = hospitalVisitService.getDatasByOracle(mrId,visitNumber);
		if (resultDatas.isSuccess()) {
			List<Map<String, Object>> datas = (List<Map<String, Object>>)resultDatas;
			hospitalVisitService.insertHospitalVisitRecords(datas,currentUser);
			RespondResult respondResult = new RespondResult(true,"200","提取成功！",null);
			model.addAttribute("respondResultJson", JsonUtil.objectToJson(respondResult));
		} else {
			RespondResult respondResult = new RespondResult(true,"500", resultDatas.getMsg(), null);
			model.addAttribute("respondResultJson", JsonUtil.objectToJson(respondResult));
		}
		
		List<Map<String, Object>> datas = null;
		if((outHospitalStartDate != null && outHospitalStartDate != "")|| ( outHospitalEndDate!=null && outHospitalEndDate != "")||(patientId!=null && patientId!="") || visitNum!=null){
			datas = hospitalVisitService.queryOracleMedicalHospitalVisit(outHospitalStartDate,outHospitalEndDate,patientId,visitNum,null);
			for (Map<String, Object> data : datas) {
				String dataMrId = (String)data.get("MRID");
				BigDecimal dataVisitNumber = (BigDecimal)data.get("VISITNUMBER");
				String dataOnlyId = (String)data.get("ONLYID");
				int count = hospitalVisitService.getHospitalizationNoteCountByMrIdAndOnlyId(dataMrId,dataVisitNumber.intValue());
				if(count > 0){
					data.put("new_record", "0");
				}else{
					data.put("new_record", "1");
				}
			}
		}
		String jsonData = JsonUtil.objectToJson(datas);
		model.addAttribute("jsonData", jsonData);
		model.addAttribute("outHospitalStartDate", outHospitalStartDate);
		model.addAttribute("outHospitalEndDate", outHospitalEndDate);
		return "query/queryHospitalVisit";
	}
	
	@RequestMapping("/exportMedicalHospitalRecord")
	@ResponseBody
	public String exportMedicalHospitalRecord(HttpServletRequest request,Model model){
		String userId = CookieUtils.getCookieValue(request, "TT_TOKEN");
		String userName = CookieUtils.getCookieValue(request, "userName");
		User currentUser = new User();
		currentUser.setLoginName(userId);
		currentUser.setName(userName);
		List<Map<String, Object>> datas = hospitalVisitService.getDatasByOracle();
		hospitalVisitService.insertHospitalVisitRecords(datas,currentUser);
		return null;
	}
	
	
	
	/**
	 * 同步疾病信息
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@PostMapping("/ajaxSynchronizDiagInfo")
	@ResponseBody
	public String ajaxSynchronizDiseaseDiagInfo(HttpServletRequest request,HttpServletResponse response,Model model){
		response.setHeader("Access-Control-Allow-Origin", "*");
		RespondResult respondResult = null;
		try{
			BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), "utf-8"));  
			StringBuffer sb = new StringBuffer("");  
			String temp;  
			while ((temp = br.readLine()) != null) {  
				sb.append(temp);  
			}  
			br.close();
			String postDataJson = sb.toString();
			Map<String, Object> postData = JsonUtil.jsonToPojo(postDataJson, Map.class);
			String mrId= (String)postData.get("mrId");
			String visitNumber= (String)postData.get("visitNumber");
			List<Map<String, Object>> diseaseDiagRecords = (List<Map<String, Object>>)postData.get("diseaseDiagRecords");
			hospitalVisitService.synchronizDiseaseDiagInfo(diseaseDiagRecords, mrId, visitNumber);
			respondResult = new RespondResult(true,"200","成功","");
		}catch (Exception e) {
			// TODO: handle exception
			e.getStackTrace();
			respondResult = new RespondResult(false,"500",e.getMessage(),"");
		}
		return JsonUtil.objectToJson(respondResult);
	}
	
	@SuppressWarnings("unchecked")
	@PostMapping("/ajaxSynchronizAllergyDrugsInfo")
	@ResponseBody
	public String ajaxSynchronizAllergyDrugsInfo(HttpServletRequest request,HttpServletResponse response,Model model){
		response.setHeader("Access-Control-Allow-Origin", "*");
		RespondResult respondResult = null;
		try{
			BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), "utf-8"));  
			StringBuffer sb = new StringBuffer("");  
			String temp;  
			while ((temp = br.readLine()) != null) {  
				sb.append(temp);  
			}  
			br.close();
			String postDataJson = sb.toString();
			Map<String, Object> postData = JsonUtil.jsonToPojo(postDataJson, Map.class);
			String mrId= (String)postData.get("mrId");
			String visitNumber= (String)postData.get("visitNumber");
			String allergyDrugs=(String)postData.get("allergyDrugs");
			if(StringUtils.isNotBlank(mrId) && StringUtils.isNotBlank(visitNumber)){
				hospitalVisitService.synchronizAllergyDrugsInfo(allergyDrugs, mrId, visitNumber);
			}else{
				respondResult = new RespondResult(false,"400","识别码和流水不可为空!","");
			}
			
			respondResult = new RespondResult(true,"200","成功","");
		}catch (Exception e) {
			// TODO: handle exception
			e.getStackTrace();
			respondResult = new RespondResult(false,"500",e.getMessage(),"");
		}
		return JsonUtil.objectToJson(respondResult);
	}
	
	
	
	@SuppressWarnings("unchecked")
	@PostMapping("/ajaxSynchronizNurseInfo")
	@ResponseBody
	public String ajaxSynchronizNurseInfo(HttpServletRequest request,HttpServletResponse response,Model model){
		response.setHeader("Access-Control-Allow-Origin", "*");
		RespondResult respondResult = null;
		try{
			BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), "utf-8"));  
			StringBuffer sb = new StringBuffer("");  
			String temp;  
			while ((temp = br.readLine()) != null) {  
				sb.append(temp);  
			}  
			br.close();
			String postDataJson = sb.toString();
			Map<String, Object> postData = JsonUtil.jsonToPojo(postDataJson, Map.class);
			String mrId= (String)postData.get("mrId");
			String visitNumber= (String)postData.get("visitNumber");
			Map<String,Object> nurseInfoMap=(Map<String,Object>)postData.get("nurseInfo");
			if(StringUtils.isNotBlank(mrId) && StringUtils.isNotBlank(visitNumber)){
				hospitalVisitService.synchronizNurseDaysInfo(nurseInfoMap, mrId, visitNumber);
			}else{
				respondResult = new RespondResult(false,"400","识别码和流水不可为空!","");
			}
			
			respondResult = new RespondResult(true,"200","成功","");
		}catch (Exception e) {
			// TODO: handle exception
			e.getStackTrace();
			respondResult = new RespondResult(false,"500",e.getMessage(),"");
		}
		return JsonUtil.objectToJson(respondResult);
	}
	
	
	@SuppressWarnings("unchecked")
	@PostMapping("/ajaxSynchronizCrueInfo")
	@ResponseBody
	public String ajaxSynchronizCrueInfo(HttpServletRequest request,HttpServletResponse response,Model model){
		response.setHeader("Access-Control-Allow-Origin", "*");
		RespondResult respondResult = null;
		try{
			BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), "utf-8"));  
			StringBuffer sb = new StringBuffer("");  
			String temp;  
			while ((temp = br.readLine()) != null) {  
				sb.append(temp);  
			}  
			br.close();
			String postDataJson = sb.toString();
			Map<String, Object> postData = JsonUtil.jsonToPojo(postDataJson, Map.class);
			String mrId= (String)postData.get("mrId");
			String visitNumber= (String)postData.get("visitNumber");
			Map<String,Object> crueInfoMap=(Map<String,Object>)postData.get("cureInfo");
			if(StringUtils.isNotBlank(mrId) && StringUtils.isNotBlank(visitNumber)){
				hospitalVisitService.synchronizCrueInfo(crueInfoMap, mrId, visitNumber);
			}else{
				respondResult = new RespondResult(false,"400","识别码和流水不可为空!","");
			}
			
			respondResult = new RespondResult(true,"200","成功","");
		}catch (Exception e) {
			// TODO: handle exception
			e.getStackTrace();
			respondResult = new RespondResult(false,"500",e.getMessage(),"");
		}
		return JsonUtil.objectToJson(respondResult);
	}
	
	
	@SuppressWarnings("unchecked")
	@PostMapping("/ajaxSynchronizOperateInfo")
	@ResponseBody
	public String ajaxSynchronizOperateInfo(HttpServletRequest request,HttpServletResponse response,Model model){
		response.setHeader("Access-Control-Allow-Origin", "*");
		RespondResult respondResult = null;
		try{
			BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), "utf-8"));  
			StringBuffer sb = new StringBuffer("");  
			String temp;  
			while ((temp = br.readLine()) != null) {  
				sb.append(temp);  
			}  
			br.close();
			String postDataJson = sb.toString();
			Map<String, Object> postData = JsonUtil.jsonToPojo(postDataJson, Map.class);
			String mrId= (String)postData.get("mrId");
			String visitNumber= (String)postData.get("visitNumber");
			List<Map<String, Object>> operateRecords = (List<Map<String, Object>>)postData.get("operateRecords");
			hospitalVisitService.synchronizOperateInfo(operateRecords, mrId, visitNumber);
			respondResult = new RespondResult(true,"200","成功","");
		}catch (Exception e) {
			// TODO: handle exception
			e.getStackTrace();
			respondResult = new RespondResult(false,"500",e.getMessage(),"");
		}
		return JsonUtil.objectToJson(respondResult);
	}
	
	/*@GetMapping("/ajaxSynchronizDiagInfo1")
	@ResponseBody
	public String ajaxSynchronizDiseaseDiagInfo1(HttpServletRequest request,Model model){
		HospitalVisitDiseaseDiagInfo diseaseDiagInfo = new HospitalVisitDiseaseDiagInfo();
		HospitalVisitDiseaseDiagRecord hospitalVisitDiseaseDiagRecord = new HospitalVisitDiseaseDiagRecord();
		hospitalVisitDiseaseDiagRecord.setDiagTypeCode("1");
		hospitalVisitDiseaseDiagRecord.setDiagSortIndex(1);
		hospitalVisitDiseaseDiagRecord.setDiseaseDiagOriginalDesc("脂肪肝");
		hospitalVisitDiseaseDiagRecord.setConfirmedDateTime(new Date());
		hospitalVisitDiseaseDiagRecord.setTreatDayNumber(BigDecimal.ONE);
		hospitalVisitDiseaseDiagRecord.setTreatResultName("未愈");
		hospitalVisitDiseaseDiagRecord.setOperateMarkCode("1");
		hospitalVisitDiseaseDiagRecord.setDiseaseDiagCode("F1235");
		diseaseDiagInfo.getDiseaseDiagRecords().add(hospitalVisitDiseaseDiagRecord);
		hospitalVisitService.synchronizDiseaseDiagInfo(new HospitalVisitDiseaseDiagInfo(), "BN0001", "1");
		return null;
	}*/
	
	@RequestMapping("/exportTable")
	public String exportTable(Model model){
		
		List<Result> list = new ArrayList<>();
		
		List<Map<String,Object>> otherList = new ArrayList<>();
		
		/*
		//身份信息
		List<Map<String, Object>> identitys = exportDataService.getIdentityByOracle();
		
		if(!identitys.isEmpty()){
			Map<String,Object> dataMap = new HashMap<>();
			dataMap.put("tableName",MysqlDataTable.IDENTITY);
			dataMap.put("datas", identitys);
			dataMap.put("oracleTableName", OracleDataTable.IDENTITY);
			otherList.add(dataMap);
		}else{
			list.add(new Result(true,"无数据可导入",OracleDataTable.IDENTITY));
		}
		List<Map<String, Object>> clinics = exportDataService.getClinicAttrByOracle();
		if(!clinics.isEmpty()){
			Map<String,Object> dataMap = new HashMap<>();
			dataMap.put("tableName",MysqlDataTable.OFFICECLINICATTR);
			dataMap.put("datas", clinics);
			dataMap.put("oracleTableName", OracleDataTable.DEPTCLINICATTR);
			otherList.add(dataMap);
		}else{
			list.add(new Result(false,"无数据可导入",OracleDataTable.DEPTCLINICATTR));
		}
		
		List<Map<String, Object>> internalOuts = exportDataService.getInternalOutByOracle();
		
		if(!internalOuts.isEmpty()){
			Map<String,Object> dataMap = new HashMap<>();
			dataMap.put("tableName",MysqlDataTable.OFFICEINTERNALOUTATTR);
			dataMap.put("datas", internalOuts);
			dataMap.put("oracleTableName", OracleDataTable.DEPTISATTR);
			otherList.add(dataMap);
		}else{
			list.add(new Result(false,"无数据可导入",OracleDataTable.DEPTISATTR));
		}
		
		List<Map<String, Object>> outPAttrs = exportDataService.getOutpByOracle();
		
		if(!outPAttrs.isEmpty()){
			Map<String,Object> dataMap = new HashMap<>();
			dataMap.put("tableName",MysqlDataTable.OFFICEOUTPATTR);
			dataMap.put("datas", outPAttrs);
			dataMap.put("oracleTableName", OracleDataTable.DEPTOIATTR);
			otherList.add(dataMap);
		}else{
			list.add(new Result(false,"无数据可导入",OracleDataTable.DEPTOIATTR));
		}
		 */
		List<Map<String,Object>> listDatas = new ArrayList<>();
		
		//性别
		listDatas.addAll(exportDataByTableName(list,OracleDataTable.SEX,MysqlDataTable.SEX));
		
		//婚姻
		listDatas.addAll(exportDataByTableName(list,OracleDataTable.MARRIAGE,MysqlDataTable.MARRIAGE));
		
		//民族
		listDatas.addAll(exportDataByTableName(list,OracleDataTable.NATION,MysqlDataTable.NATION));
		
		//血型
		listDatas.addAll(exportDataByTableName(list,OracleDataTable.BLOODTYPE,MysqlDataTable.BLOODTYPE));
		
		//职业分类
		listDatas.addAll(exportDataByTableName(list,OracleDataTable.OCCUPATION,MysqlDataTable.PROFESSION));
		
		//国家
		listDatas.addAll(exportDataByTableName(list,OracleDataTable.COUNTRY,MysqlDataTable.NATIONALITY));
		
		//地区
		listDatas.addAll(exportDataByTableName(list,OracleDataTable.AREA,MysqlDataTable.AREA));
		
		
		//入院方式
		listDatas.addAll(exportDataByTableName(list,OracleDataTable.PATIENTCLASS,MysqlDataTable.INHOSPTYPE));
		
		//出院方式
		listDatas.addAll(exportDataByTableName(list,OracleDataTable.DISCHARGEMODE,MysqlDataTable.OUTHOSTYPE));
		
		//社会关系
		listDatas.addAll(exportDataByTableName(list,OracleDataTable.RELATIONSHIP,MysqlDataTable.RELATIVERELATION));
		
		//切口愈合
		listDatas.addAll(exportDataByTableName(list,OracleDataTable.WOUNDHEALING,MysqlDataTable.WOUNDHEALINGTYPE));
		
		//手术等级
		listDatas.addAll(exportDataByTableName(list,OracleDataTable.OPERATIONLEVEL,MysqlDataTable.OPERATIONLEVEL));
		
		//治疗结果
		listDatas.addAll(exportDataByTableName(list,OracleDataTable.TREATINGRESULT,MysqlDataTable.TREATINGRESULT));
		
		//切口等级
		listDatas.addAll(exportDataByTableName(list,OracleDataTable.WOUNDLEVEL,MysqlDataTable.WOUNDLEVEL));
		
		//诊断类型
		listDatas.addAll(exportDataByTableName(list,OracleDataTable.DIAGNOSETYPE,MysqlDataTable.DIAGNOSETYPE));
		//麻醉方式
		listDatas.addAll(exportDataByTableName(list,OracleDataTable.ANAESTHESIA,MysqlDataTable.ANAESTHESIAWAY));
		
		
		
		//入院时病情
		List<Map<String, Object>> inHosStates = exportDataService.getInHospStatusByOracle();

		if(!inHosStates.isEmpty()){
			Map<String,Object> dataMap = new HashMap<>();
			dataMap.put("tableName",MysqlDataTable.INHOSSTATE);
			dataMap.put("datas", inHosStates);
			dataMap.put("oracleTableName", OracleDataTable.ILLNESSSTATE);
			otherList.add(dataMap);
		}else{
			list.add(new Result(false,"无数据可导入",OracleDataTable.ILLNESSSTATE));
		}
		
		//技术职务
		List<Map<String, Object>> titiles = exportDataService.getTitileByOracle();

		if(!titiles.isEmpty()){
			Map<String,Object> dataMap = new HashMap<>();
			dataMap.put("tableName",MysqlDataTable.MEDICAL_PROFESSIONAL_TITLE);
			dataMap.put("datas", titiles);
			dataMap.put("oracleTableName", OracleDataTable.TITLE);
			otherList.add(dataMap);
		}else{
			list.add(new Result(false,"无数据可导入",OracleDataTable.TITLE));
		}
		
		//工作职业
		List<Map<String, Object>> jobClass = exportDataService.getJobClassByOracle();

		if(!jobClass.isEmpty()){
			Map<String,Object> dataMap = new HashMap<>();
			dataMap.put("tableName",MysqlDataTable.MEDICAL_PROFESSION);
			dataMap.put("datas", jobClass);
			dataMap.put("oracleTableName", OracleDataTable.JOB_CLASS);
			otherList.add(dataMap);
		}else{
			list.add(new Result(false,"无数据可导入",OracleDataTable.JOB_CLASS));
		}
		
		
		
		//科室
		List<Map<String, Object>> offices = exportDataService.getOfficeByOracle();
		
		if(!offices.isEmpty()){
			Map<String,Object> dataMap = new HashMap<>();
			dataMap.put("tableName",MysqlDataTable.MEDICALOFFICE);
			dataMap.put("datas", offices);
			dataMap.put("oracleTableName", OracleDataTable.DEPT);
			otherList.add(dataMap);
		}else{
			list.add(new Result(false,"无数据可导入",OracleDataTable.DEPT));
		}
		
		
		
		//费用类别
		List<Map<String, Object>> chargeTypes = exportDataService.getChargeTypeByOracle();
		
		if(!chargeTypes.isEmpty()){
			Map<String,Object> dataMap = new HashMap<>();
			dataMap.put("tableName",MysqlDataTable.PAYMENT_TYPE);
			dataMap.put("datas", chargeTypes);
			dataMap.put("oracleTableName", OracleDataTable.CHARGE_TYPE);
			otherList.add(dataMap);
		}else{
			list.add(new Result(false,"无数据可导入",OracleDataTable.CHARGE_TYPE));
		}
		//诊断符合
		listDatas.addAll(exportDataByTableName(list,OracleDataTable.DIAG_CORR,MysqlDataTable.DIAGNOSTIC_COINCIDENCE_TYPE));
		
		
		//国际疾病
		List<Map<String, Object>> diagnosiss = exportDataService.getDiagnosisByOracle();
		
		if(!diagnosiss.isEmpty()){
			Map<String,Object> dataMap = new HashMap<>();
			dataMap.put("tableName",MysqlDataTable.DISEASE);
			dataMap.put("datas", diagnosiss);
			dataMap.put("oracleTableName", OracleDataTable.DIAGNOSIS);
			otherList.add(dataMap);
		}else{
			list.add(new Result(false,"无数据可导入",OracleDataTable.DIAGNOSIS));
		}
		//手术
		List<Map<String, Object>> operations = exportDataService.getOperationsByOracle();
		
		if(!operations.isEmpty()){
			Map<String,Object> dataMap = new HashMap<>();
			dataMap.put("tableName",MysqlDataTable.OPERATION);
			dataMap.put("datas", operations);
			dataMap.put("oracleTableName", OracleDataTable.OPERATION);
			otherList.add(dataMap);
		}else{
			list.add(new Result(false,"无数据可导入",OracleDataTable.OPERATION));
		}
		
		List<Map<String, Object>> staffs = exportDataService.getStaffsByOracle();
		if(!staffs.isEmpty()){
			Map<String,Object> dataMap = new HashMap<>();
			dataMap.put("tableName",MysqlDataTable.MEDICAL_WORKER);
			dataMap.put("datas", staffs);
			dataMap.put("oracleTableName", OracleDataTable.STAFF);
			otherList.add(dataMap);
		}else{
			list.add(new Result(false,"无数据可导入",OracleDataTable.STAFF));
		}
		
		
		
//		List<Map<String, Object>> medicalRecords = exportDataService.getOracleMedicalHospitalRecord();
//		exportDataService.insertMysqlMedicalHospitalRecord(medicalRecords);
		list.addAll(exportDataService.inserDataTable(listDatas,otherList));
		model.addAttribute("results", list);
		return "export/exportbasic";
	}
	
	public List<Map<String,Object>> exportDataByTableName(List<Result> results,String oracleTableName,String insertTableName){
		List<Map<String, Object>> listData = new ArrayList<>();
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("prefix", oracleTableName.substring(0,oracleTableName.lastIndexOf("_DICT")));
		map.put("tableName", oracleTableName);
		List<Map<String, Object>> datas = exportDataService.getDataByOracle(map);
		
		if(!datas.isEmpty()){
			Map<String,Object> dataMap = new HashMap<>();
			dataMap.put("tableName",insertTableName);
			dataMap.put("datas", datas);
			dataMap.put("oracleTableName", oracleTableName);
			listData.add(dataMap);
		}else{
			results.add(new Result(false,"无数据可导入",oracleTableName));
		}
		
		return listData;
	}
	
	@ResponseBody
	@GetMapping("/remote_query_patient_index")
	public RespondResult remoteQueryPatientIndex(@RequestParam(value = "paramDatas") String[] paramDatas,HttpServletResponse response){
		RespondResult respondResult = null;
		try{
			response.setHeader("Access-Control-Allow-Origin", "*");
			List<Map<String,Object>> patientIndexs = new ArrayList<Map<String,Object>>();
			for (String paramData : paramDatas) {
				String[] splits = paramData.split("-");
				String mrId = splits[0];
				String visitNumber = splits[1];
				
				if(visitNumber!=null && visitNumber.trim().length() > 0){
					List<Map<String,Object>> datas = hospitalVisitService.queryOracleMedicalHospitalVisit(null, null,mrId,Integer.parseInt(visitNumber),null);
					if(!datas.isEmpty()){
						patientIndexs.add(datas.get(0));
					}
					/*Map<String,Object> data = new HashMap<String,Object>();
					data.put("MRID", "D261718");
					data.put("VISITNUMBER", "6");
					data.put("INHOSPITALNDATETIME", "2018-10-22");
					data.put("INDEPTCODE", "11");
					data.put("OUTDEPTCODE", "11");
					data.put("OUTHOSPITALDATETIME", "2018-10-22");
					data.put("PATIENTNAME", "张三");*/
					
					
					//patientIndexs.add(data);
					
				}
			}
			respondResult = new RespondResult(true, RespondResult.successCode, null, patientIndexs);
		}
		catch (Exception e) {
			e.printStackTrace();
			respondResult = new RespondResult(false, RespondResult.errorCode, ExceptionUtil.getStackTrace(e), null);
		}
		return respondResult;
	}
	
	
	@ResponseBody
	@GetMapping("/remote_fetch_data_for_scan")
	public RespondResult remoteFetchDataForScan(String visitGuid,String mrId,Integer visitNumber,HttpServletResponse response){
		RespondResult respondResult = null;
		try{
			response.setHeader("Access-Control-Allow-Origin", "*");
			Result resultDatas = hospitalVisitService.getDatasByOracle(mrId,visitNumber,visitGuid);
			if (resultDatas.isSuccess()) {
				List<Map<String, Object>> datas = (List<Map<String, Object>>)resultDatas.getData();
				User currentUser = new User();
				currentUser.setLoginName("yyl");
				currentUser.setName("叶永利");
				hospitalVisitService.insertHospitalVisitRecords(datas,currentUser,visitGuid);
				respondResult = new RespondResult(true, RespondResult.successCode, null, "成功");
			}else{
				respondResult = new RespondResult(false, RespondResult.errorCode,"失败", null);
			}
			
			
		}
		catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			respondResult = new RespondResult(false, RespondResult.errorCode, e.getMessage(), null);
		}
		return respondResult;
	}
	
}







